import React, {useState,useEffect} from "react";
import {get, map, trim} from "lodash";
import Modal from "antd/lib/modal";
import Form from "antd/lib/form";
import Checkbox from "antd/lib/checkbox";
import Row from "antd/lib/row";
import Col from "antd/lib/col";
import Select from "antd/lib/select";
import Button from "antd/lib/button";
import Divider from "antd/lib/divider";
import { wrap as wrapDialog, DialogPropType } from "@/components/DialogWrapper";
import DynamicComponent from "@/components/DynamicComponent";
import {UserProfile} from "@/components/proptypes";
import Workflow_transition from "@/services/workflow_transition";
import notification from "@/services/notification";
import {useGroupItems}  from "@/services/group";
import {useStateItems,useUserItems,useColItems} from "@/services/workflow_state";
import Workflow_state from "@/services/workflow_state";
import {currentUser} from "@/services/auth";
import CreateStateDialog from "@/components/workflow/StateDialog";
import WarningOutlined from "@ant-design/icons/WarningOutlined";
const { confirm } = Modal;


function CreateTransitionDialog({ transition, dialog }) {
  const {userLoaded, userdata } = useUserItems('params');
  const {groupLoaded, groupdata } = useGroupItems('params');
  const {colLoaded, coldata } = useColItems('contracts');
  const {stateLoaded, statedata } = useStateItems(transition.workflowid);
  const [dataLoaded, setDataLoaded] = useState(transition.id ===0 ? true : false);
  const [workflow_stateid, setworkflow_stateid] = useState("");
  const [next_workflow_stateid, setnext_workflow_stateid] = useState("");
  const [next_type, setnext_type] = useState("1");
  const [allow_user, setallow_user] = useState([]);
  const [allow_group, setallow_group] = useState([]);
  const [allow_col, setallow_col] = useState([]);
  const [condition, setcondition] = useState("");
  const [isValid, setIsValid] = useState(false);
  const [saveInProgress, setSaveInProgress] = useState(false);
  const isCreateTransitionEnabled = useState(true);//policy.isAdmin() || policy.isDefault();
  useEffect(() => {
    if (transition.id === 0) return;
    let cancelLoading = false;
    if (!cancelLoading) {
      setworkflow_stateid(transition.workflow_stateid);
      setnext_workflow_stateid(transition.next_workflow_stateid);
      setnext_type(transition.next_type);
      setallow_user(transition.allow_user);
      setallow_group(transition.allow_group);
      setallow_col(transition.allow_col);
      setcondition(transition.condition);
      setDataLoaded(true);
    }
    // params={
    //   page: 1,
    //   page_size: 100,
    //   name: "",
    // }
    // Workflow_state.getlist(params).then(data => {
    //     setstatedata(data.data);
    //     setDataLoaded(true);
    // });
    return () => {
      cancelLoading = true;
    };
  }, [transition]);

  function handlestateChange(event) {
    const value = trim(event);
    setworkflow_stateid(value);
    setIsValid(value !== "" && next_workflow_stateid !== "" );
  }
  function handlenextstateChange(event) {
    const value = trim(event);
    setnext_workflow_stateid(value);
    setIsValid(value !== "" && workflow_stateid !== "" );
  }

  function handlenext_typeChange(event) {
    const value = trim(event);
    setnext_type(value);
    setIsValid(workflow_stateid !== "" && next_workflow_stateid !== "");
  }
  function handleallow_colChange(checkedValues) {
    setallow_col(checkedValues);
    setIsValid(workflow_stateid !== "");
  }
  function handleallow_userChange(checkedValues) {
    setallow_user(checkedValues);
    setIsValid(workflow_stateid !== "" && next_workflow_stateid !== "" );
  }
  function handleallow_groupChange(checkedValues) {
    setallow_group(checkedValues);
    setIsValid(workflow_stateid !== "" && next_workflow_stateid !== "");
  }
   function handleconditionChange(event) {
    const value = trim(event.target.value);
    setcondition(value);
    setIsValid(workflow_stateid !== "" && next_workflow_stateid !== "" );
  }
  function showCreateStateDialog(id){
    CreateStateDialog.showModal({state_id: id})
    .onClose((result = {}) => {
        if (result.success) {
        }
      }).onDismiss(() => {
      });
  };
  function handleDelete() {
    
    let item = statedata.filter((p) => {
      return p.id === workflow_stateid;
    });
    if(item.length<1){
      notification.warn("状态已删除");
      return;
    }
    if(item[0].docstatus !==1){
      notification.error("开始和结束状态不能删除");
      return;
    }
    const params={id: workflow_stateid};
    confirm({
      title: '确定删除状态?',
      icon: <WarningOutlined />,
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        Workflow_state.delete(params).then(()=>{
          notification.success("状态删除成功.");
        }).catch(error => {
          notification.error(get(error, "response.data.message", "删除失败."));
        });
      },
    });
  };
  function handleSubmit() {
    setSaveInProgress(true);
    let params={
      id: transition.id,
      userid: currentUser.id,
      workflowid: transition.workflowid,
      workflow_stateid: workflow_stateid,
      next_workflow_stateid: next_workflow_stateid,
      next_type: next_type,
      allow_user: allow_user,
      allow_group: allow_group,
      allow_col: allow_col,
      condition: condition,
    }
    if (transition.id === 0) {
      Workflow_transition.create(params)
        .then(() => {
          dialog.close({ success: true});
        })
        .catch(error => {
          notification.error(error.message, error.detailedMessage);
          setSaveInProgress(false);
        });
    } else {
      Workflow_transition.save(params)
        .then(() => {
          dialog.close({ success: true});
        })
        .catch(error => {
          notification.error(error.message, error.detailedMessage);
          setSaveInProgress(false);
        });
    }
  }
  return (
    <Modal
      {...dialog.props}
      {...(isCreateTransitionEnabled ? {} : { footer: null })}
      title="流程动作"
      width={document.querySelector('body').offsetWidth*0.5}
      okText="保存"
      cancelText="取消"
      okButtonProps={{
        disabled:  !isValid || saveInProgress,
        loading: saveInProgress,
        "data-test": "DashboardSaveButton",
      }}
      cancelButtonProps={{
        disabled: saveInProgress,
      }}
      onOk={handleSubmit}
      closable={!saveInProgress}
      maskClosable={!saveInProgress}
      wrapProps={{
        "data-test": "CreateDashboardDialog",
      }}>
      {dataLoaded && (
      <DynamicComponent name="CreateTransitionDialogExtra" disabled={!isCreateTransitionEnabled}>
      <Form layout="horizontal" {...{labelCol: { span: 4 }, wrapperCol: { span: 14 },} }>
         <Row>
				  <Col span={10}>
            {stateLoaded && (
            <Form.Item style={{ marginBottom: 5 }} label="状态">
              <Select
                showSearch
                optionFilterProp="children" 
                style={{ width:  300 }} 
                defaultValue={workflow_stateid} 
                onChange={handlestateChange} 
                disabled={saveInProgress}
              >
                {map(statedata, ds => (
                  <Select.Option key={ds.id} value={ds.id}>{ds.name}</Select.Option>
                ))}
              {/*{statedata.map(item => (*/}
              {/*  <Select.Option key={item.id} value={item.id}>{item.name}</Select.Option>*/}
              {/*))}*/}
              </Select>
            </Form.Item>
            )}
				  </Col>
          <Col span={10}>
            <Button type="primary" onClick={() => showCreateStateDialog(0)}>
              <i className="fa fa-plus m-r-5" />
              新建
            </Button>
          <Divider type="vertical" />
          <Button type="primary" onClick={() => showCreateStateDialog(workflow_stateid)} >
            <i className="fa fa-save m-r-5" />
            修改
          </Button>
          <Divider type="vertical" />
          <Button type="primary" onClick={() => handleDelete()} >
            <i className="fa fa-trash m-r-5" />
            删除
          </Button>
				  </Col>
        </Row>
       <Row>
        <Col span={10}>
        <Form.Item style={{ marginBottom: 5 }} label="行动">
              <Select style={{ width:  300 }} defaultValue={next_type} onChange={handlenext_typeChange} disabled={saveInProgress}>
                <Select.Option key="1" value="1">同意</Select.Option>
                <Select.Option key="2" value="2">拒绝</Select.Option>
              </Select>
        </Form.Item>
        </Col>
      </Row>
         <Row>
				  <Col span={10}>
            {stateLoaded && (
            <Form.Item style={{ marginBottom: 5 }} label="下一状态">
              <Select 
                showSearch
                optionFilterProp="children"
                style={{ width:  300 }} 
                defaultValue={next_workflow_stateid} 
                onChange={handlenextstateChange} 
                disabled={saveInProgress}
              >
                {map(statedata, ds => (
                  <Select.Option key={ds.id} value={ds.id}>{ds.name}</Select.Option>
                ))}
              </Select>
            </Form.Item>
            )}
				  </Col>
        </Row>
       <Row>
        <Col span={10}>
          <p>允许审批</p>
        </Col>
      </Row>
       <Row>
        <Col span={24}>
        {userLoaded && (
        <Form.Item style={{ marginBottom: 2 }} label="用户">
        <Checkbox.Group
          loading={!userLoaded} style={{ width: '100%' }} 
          defaultValue={allow_user}
          onChange={handleallow_userChange}>
          &nbsp;&nbsp;&nbsp;
          {map(userdata, ds => (
             <Checkbox style={{ width: "100px" }} value={ds.id}>{ds.name}</Checkbox>

          ))}
          
        </Checkbox.Group>

        </Form.Item>
        )}
        </Col>
      </Row>
      <Row>
        <Col span={24}>
        {groupLoaded && (
        <Form.Item style={{ marginBottom: 2 }} label="权限组">
        <Checkbox.Group
          loading={!groupLoaded} style={{ width: '100%' }} 
          defaultValue={allow_group}
          onChange={handleallow_groupChange}>
            &nbsp;&nbsp;&nbsp;
          {map(groupdata, ds => (
            <Checkbox style={{ width: "100px" }} value={ds.id}>{ds.name}</Checkbox>
          ))}
          
        </Checkbox.Group>
        </Form.Item>
        )}
        </Col>
      </Row>
      <Row>
        <Col span={10}>
          <p>允许编辑</p>
        </Col>
      </Row>
       <Row>
        <Col span={24}>
        {colLoaded && (
        <Form.Item style={{ marginBottom: 2 }} label="编辑字段">
        <Checkbox.Group
          loading={!colLoaded} style={{ width: '100%' }} 
          defaultValue={allow_col}
          onChange={handleallow_colChange}>
          {map(coldata, ds => (
            <Checkbox style={{ width: "100px" }} value={ds.code}>{ds.name}</Checkbox>
          ))}
          
        </Checkbox.Group>
        </Form.Item>
        )}
        </Col>
      </Row>
        <Row >
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="条件">
              <textarea
                rows="5" cols="60"
                textAlignVertical="top"
                height="100px"
                defaultValue={condition}
                onChange={handleconditionChange}
                placeholder="条件"
                disabled={saveInProgress}
              />
						</Form.Item>
				  </Col>
        </Row>
      </Form>
      </DynamicComponent>
      )}
    </Modal>
  );
}

CreateTransitionDialog.propTypes = {
  transition: UserProfile.isRequired,
  dialog: DialogPropType.isRequired,
};

export default wrapDialog(CreateTransitionDialog);
